﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler
{
    public class CreateMenuCommendHandlers : IRequestHandler<CreateMenuCommends, APIResult<Menu>>
    {
        private readonly IBaseRepository<Menu> menuRepository;
        private readonly IMapper mapper;

        public CreateMenuCommendHandlers(IBaseRepository<Menu> menuRepository, IMapper mapper)
        {
            this.menuRepository = menuRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加菜单数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<Menu>> Handle(CreateMenuCommends request, CancellationToken cancellationToken)
        {
            APIResult<Menu> result = new APIResult<Menu>();
            var menu = mapper.Map<Menu>(request);
            menu.IsDel= false;
            menu.CreateName = request.CreateName;
            menu.CreateTime = DateTime.Now;
            menu.UpdateTime = null;
            var data=menuRepository.GetAllAsync().Result.FirstOrDefault(p=>p.ParentMenuId==request.ParentMenuId&&p.MenuName==request.MenuName);
            if (data == null)
            {
                result.Code = APIEnum.添加成功;
                result.Msg=APIEnum.添加成功.ToString();
                await menuRepository.Add(menu);
                result.data = menu;
            }
            else 
            {
                result.Code = APIEnum.菜单名称重复;
                result.Msg = APIEnum.菜单名称重复.ToString();
                result.data = data;
            }

            return await Task.FromResult(result);
        }
    }
}
